package com.app.util;


import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * @description: MD5工具类
 * @author: N
 * @create: 2021-05-31 17:20:10
 **/
public class Md5Util {

    private static final String[] hexDigits = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    static final char hexDigits2[] = { '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    /**
     * 获取MD5加密结果
     *
     * @param plainText   要加密的原字符串
     * @param charsetName 编码类型一般是:UTF-8
     * @param uppercase   是否转为大写字符串
     * @param bit         加密结果位数（16，32）,默认是32
     * @return 返回加密结果
     */
    public static String getMd5(String plainText, String charsetName, boolean uppercase, Integer bit) {
        byte[] btInput = plainText.getBytes(StandardCharsets.UTF_8);
        MessageDigest messageDigest;
        try {
            //获得MD5摘要对象
            messageDigest = MessageDigest.getInstance("MD5");
            //使用指定的字节数组更新摘要信息
            messageDigest.update(btInput);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5签名过程中出现错误,算法异常");
        }
        byte[] digest = messageDigest.digest();
        //字节数组转成16进制字符串
        String result = byteArrayToHexString(digest);
        //如果获取的是16位加密结果的，则截取原加密结果（32位）中间的16位，也就是8-24位
        if (bit != null && bit == 16) {
            //截取下标从0开始
            result = result.substring(8, 24);
        }
        //结果的大小写处理
        return uppercase ? result.toUpperCase() : result;
    }

    /**
     * 字节数组转成16进制字符串
     *
     * @param bytes 要转换的字节数组
     * @return
     */
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            builder.append(byteToHexString(b));
        }
        return builder.toString();
    }

    /**
     * 字节转成16进制字符
     *
     * @param b 要转换的字节
     * @return
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * 生成MD5码
     *
     * @param plainText
     *            要加密的字符串
     * @return md5值
     */
    public final static String MD5(String plainText) {
        try {
            byte[] strTemp = plainText.getBytes("UTF-8");
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits2[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits2[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 生成MD5码
     *
     * @param plainText
     *            要加密的字符串
     * @return md5值
     */
    public final static String MD5(byte[] plainText) {
        try {
            byte[] strTemp = plainText;
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits2[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits2[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 先进行HmacSHA1转码再进行Base64编码
     * @param data  要SHA1的串
     * @param key   秘钥
     * @return
     * @throws Exception
     */
    public static String HmacSHA1ToBase64(String data, String key) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }

    /**
     * 校验MD5码
     *
     * @param text
     *            要校验的字符串
     * @param md5
     *            md5值
     * @return 校验结果
     */
    public static boolean valid(String text, String md5) {
        return md5.equals(MD5(text)) || md5.equals(MD5(text).toUpperCase());
    }

    /**
     *
     * @param params
     * @return
     */
    public static String MD5(String... params) {
        StringBuilder sb = new StringBuilder();
        for (String param : params) {
            sb.append(param);
        }
        return MD5(sb.toString());
    }


}